// miniprogram/pages/detail/detail.js
var WxParse = require('../../wxParse/wxParse.js');
// 获取全局唯一的背景音频管理器
const backgroundAudioManager = wx.getBackgroundAudioManager()
let isMoving = false
let duration = 0 // 当前歌曲的总时长，以秒为单位
let currentSec = -1 // 当前的秒数

Page({
  data: {
    id: '',
    detail: '',
    audioCtx: '',
    control: 'stop',
    isPlaying: false,
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00',
      surplusTime: '00:00'
    }
  },

  onLoad: function (options) {
    this._options = options
    if (options.type == 1) {
      this.getEssayDetail()
    } else if (options.type == 2) {
      this.getSerialDetail()
    } else if (options.type == 5) {
      this.getMovieDetail()
    }
    this._bindBGMEvent()
  },
  handleControl() {
    let detail = this.data.detail
    backgroundAudioManager.src = detail.audio
    backgroundAudioManager.title = detail.title
    backgroundAudioManager.singer = detail.anchor
    this.togglePlaying()
  },
  togglePlaying() {
    // 正在播放
    console.log('切换')
    if (this.data.isPlaying) {
      backgroundAudioManager.pause()
    } else {
      backgroundAudioManager.play()
    }
    this.setData({
      isPlaying: !this.data.isPlaying
    })
  },
  _setTime() {
    duration = backgroundAudioManager.duration
    const durationFmt = this._dateFormat(duration)
    this.setData({
      ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`
    })
  },
  _bindBGMEvent() {
    backgroundAudioManager.onPlay(() => {
      console.log('onPlay')
      isMoving = false
      this.triggerEvent('musicPlay')
    })

    backgroundAudioManager.onStop(() => {
      console.log('onStop')
    })

    backgroundAudioManager.onPause(() => {
      console.log('Pause')
      this.triggerEvent('musicPause')
    })

    backgroundAudioManager.onWaiting(() => {
      console.log('onWaiting')
    })

    backgroundAudioManager.onCanplay(() => {
      console.log('onCanplay')
      // console.log(backgroundAudioManager.duration)
      if (typeof backgroundAudioManager.duration != 'undefined') {
        this._setTime()
      } else {
        setTimeout(() => {
          this._setTime()
        }, 1000)
      }
    })

    backgroundAudioManager.onTimeUpdate(() => {
      // console.log('onTimeUpdate')
      if (!isMoving) {
        const currentTime = backgroundAudioManager.currentTime
        const duration = backgroundAudioManager.duration
        const sec = currentTime.toString().split('.')[0]
        if (sec != currentSec) {
          // console.log(currentTime)
          let surplusTimeFmt = this._dateFormat(parseInt(this.data.detail.audio_duration - currentTime))
          const currentTimeFmt = this._dateFormat(currentTime)
          this.setData({
            // movableDis: (movableAreaWidth - movableViewWidth) * currentTime / duration,
            // progress: currentTime / duration * 100,
            ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`,
            ['showTime.surplusTime']: `${surplusTimeFmt.min}:${surplusTimeFmt.sec}`,
          })
          currentSec = sec
        }
      }
    })

    backgroundAudioManager.onEnded(() => {
      console.log("onEnded")
      this.triggerEvent('musicEnd')
    })

    backgroundAudioManager.onError((res) => {
      console.error(res.errMsg)
      console.error(res.errCode)
      wx.showToast({
        title: '错误:' + res.errCode,
      })
    })
  },
  setContent(str) {
    return str.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
      .replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
      .replace(/<p>/ig, '<p class="p_class">')
      .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
      .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
      .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
      .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
      .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img$1 class="pho"')
  },
  setDetail(title, author, audio, audio_duration, anchor, content, author_introduce) {
    
    this.getduration(audio_duration)
    return {
      title, 
      author, 
      audio, 
      audio_duration,
      anchor,
      content: this.setContent(content),
      author_introduce: author_introduce.replace("\（", "").replace("\）", "")
    }
  },
  getduration(audio_duration) {
    const durationFmt = this._dateFormat(audio_duration)
    let duration = `${durationFmt.min}:${durationFmt.sec}`
    this.setData({
      ['showTime.surplusTime']: duration
    })
  },
  getEssayDetail() {
    wx.cloud.callFunction({
      name: 'read',
      data: {
        $url: 'essayDetail',
        id: this._options.id
      }
    }).then(res => {
      let d = res.result.data
      
      let detail = this.setDetail(d.hp_title, d.hp_author, d.audio, d.audio_duration, d.anchor, d.hp_content, d.hp_author_introduce)
      WxParse.wxParse('article', 'html', detail.content, this, 5);
      this.setData({
        detail: detail
      })
    })
  },
  getSerialDetail() {
    wx.cloud.callFunction({
      name: 'read',
      data: {
        $url: 'serialDetail',
        id: this._options.id
      }
    }).then(res => {
      let d = res.result.data
      let detail = this.setDetail(d.title, d.author.user_name, d.audio, d.audio_duration, d.anchor, d.content, d.charge_edt)
      WxParse.wxParse('article', 'html', detail.content, this, 5);
      this.setData({
        detail: detail
      })
    })
  },
  getMovieDetail() {
    wx.cloud.callFunction({
      name: 'read',
      data: {
        $url: 'movieDetail',
        id: this._options.id
      }
    }).then(res => {
      let d = res.result.data.data[0]
      let detail = this.setDetail(d.title, d.user.user_name, d.audio, d.audio_duration, d.anchor, d.content, d.charge_edt)
      
      WxParse.wxParse('article', 'html', detail.content, this, 5);
      this.setData({
        detail: detail
      })
    })
  },
  // 格式化时间
  _dateFormat(sec) {
    // 分钟
    const min = Math.floor(sec / 60)
    sec = Math.floor(sec % 60)
    return {
      'min': this._parse0(min),
      'sec': this._parse0(sec),
    }
  },
  // 补零
  _parse0(sec) {
    return sec < 10 ? '0' + sec : sec
  }
  
})